# coding=utf-8
import random
import re

from flask import current_app
from flask import make_response
from flask import render_template
from flask import request, jsonify,session

from ihome_blue import ihome_blue
from init import redis_store, db
from models import User
from utils.captcha.captcha import captcha
from utils.constants import IMAGE_CODE_REDIS_EXPIRES, SMS_CODE_REDIS_EXPIRES

#生产验证码
from utils.response_code import RET

@ihome_blue.route('/imagecode')
def image_code():
    cur = request.args.get('cur')
    pre = request.args.get('pre')
    name,text,image_data = captcha.generate_captcha()

    try:
        redis_store.set('image_code:%s'%cur,text,IMAGE_CODE_REDIS_EXPIRES)

        if pre:
            redis_store.delete('image_code:%s'%pre)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='验证码显示错误')


    response = make_response(image_data)
    response.headers['Content-Type'] = 'image/png'
    return response

#发送短信验证码
@ihome_blue.route('/smscode', methods=['POST'])
def smscode():
    moblie = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')

    if not all([moblie,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if not re.match('1[3-9]\d{9}',moblie):
        return jsonify(errno=RET.DBERR,errmsg='手机号错误')

    try:
          redis_image_code = redis_store.get('image_code:%s'%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='redis操作失败')

    if not redis_image_code:
        return jsonify(errno=RET.NODATA,errmsg='验证码以过期')

    if redis_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR,errmsg='验证码错误')

    try:
        redis_store.delete('image_code:%s'%image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='验证码删除失败')

    sms_code = '%06d'%random.randint(0, 999999)
    current_app.logger.debug('验证码是：%s'%sms_code)

    try:
        redis_store.set('sms_code:%s'%moblie,sms_code,SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='短信验证码存入失败')

    return jsonify(errno=RET.OK,errmsg='短信发送成功')

#注册
@ihome_blue.route('/user', methods=['POST'])
def user():
    mobile = request.json.get('mobile')
    phonecode = request.json.get('phonecode')
    password = request.json.get('password')

    if not all([mobile,phonecode,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    try:
        redis_sms_code = redis_store.get('sms_code:%s'%mobile)
    except Exception as e:
        return jsonify(errno=RET.DATAERR,errmsg='验证码取出失败')

    if not redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg='短信验证码已经过期')

    if redis_sms_code != phonecode:
        return jsonify(errno=RET.DBERR,errmsg='短信验证码错误')

    try:
        redis_store.delete('sms_code:%s'%mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='删除失败')

    user = User()
    user.name = mobile
    user.mobile = mobile
    user.password = password

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='用户注册失败')

    return jsonify(errno=RET.OK,errmsg='注册成功')

#登陆
@ihome_blue.route('/sessions', methods=['POST'])
def sessions():
    mobile = request.json.get('mobile')
    password = request.json.get('password')

    if not all([mobile,password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库获取失败')

    if not user:
        return jsonify(errno=RET.DBERR,errmsg='用户不存在')

    if not user.check_password(password) != password:
        return jsonify(errno=RET.DATAERR,errmsg='密码错误')

    session['user_id'] = user.id

    return jsonify(errno=RET.OK,errmsg='登陆成功')

@ihome_blue.route('/get_login', methods=['GET', 'POST'])
def get_login():
    user_id = session.get('user_id')
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    print(user)
    data = {
        'user_id': user.id,
        'name' : user.name
    }

    return jsonify(errno=RET.OK,data=data)